package com.assistant.codegen.modules.model.app;

import com.assistant.codegen.modules.model.app.cmd.ColumnInsertCmd;
import com.assistant.codegen.modules.model.app.cmd.ColumnUpdateCmd;
import com.assistant.codegen.modules.model.domain.column.ModelColumn;
import com.assistant.codegen.modules.model.domain.column.ColumnFactory;
import com.assistant.codegen.modules.model.domain.gateway.ColumnGateway;
import com.assistant.codegen.modules.model.domain.gateway.ModelGateway;
import com.assistant.framework.PageUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ColumnService {

    @Autowired
    private ColumnGateway gateway;
    @Autowired
    private ModelGateway modelGateway;

    public ModelColumn get(Long id) {
        return gateway.getById(id);
    }

    public List<ModelColumn> list(Long modelId) {
        return gateway.findAllByModel(modelGateway.getById(modelId));
    }

    public Page<ModelColumn> page(Long modelId) {
        return gateway.findAllByModel(modelGateway.getById(modelId), PageUtils.currentPage());
    }

    public ModelColumn insert(ColumnInsertCmd cmd) {
        ModelColumn column = ColumnFactory.create(cmd.getType());
        column.setModel(modelGateway.getById(cmd.getModelId()));
        BeanUtils.copyProperties(cmd, column);
        return gateway.save(column);
    }

    public void update(ColumnUpdateCmd cmd) {
        ModelColumn model = gateway.getById(cmd.getId());
        BeanUtils.copyProperties(cmd, model);
        gateway.save(model);
    }

    public void delete(Long id) {
        gateway.deleteById(id);
    }
}
